using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Nizm0.QOT.Library.UserControls
{
    public partial class ucShowProcedure : UserControl
    {
        private Library.Objects.IProcedure _procedure;

        //public event OpenFormEventHandler OpenProcedure;

        public ucShowProcedure(Library.Objects.IProcedure procedure)
        {
            InitializeComponent();
            //_procedure = procedure;

            Fill(procedure);
        }

        public ucShowProcedure()
        {
            InitializeComponent();


        }
        public void Fill(Library.Objects.IProcedure procedure)
        {
            _procedure = procedure;

            panel_Details.Controls.Clear();
            Control con = procedure.Show();
            con.Dock = DockStyle.Fill;
            //con.Location = new Point(0, 0);
            panel_Details.Size = new Size(panel_Details.Size.Width, con.Size.Height);
            panel_Details.Controls.Add(con);

            dataGridView1.Location = new Point(0, panel_Details.Size.Height + panel_Details.Location.Y);
            dataGridView1.Size = new Size(dataGridView1.Size.Width, this.Size.Height - (panel_Details.Location.Y + panel_Details.Size.Height));

            if (procedure.ListOfVariable != null)
            {
                dataGridView1.Columns.Clear();
                dataGridView1.DataSource = null;
                dataGridView1.DataSource = procedure.ListOfVariable;
                //if (dataGridView1.InvokeRequired)
                //    dataGridView1.Invoke((MethodInvoker)delegate { ((CurrencyManager)dataGridView1.BindingContext[Library.Objects.ProjectSettings.Instance.ProceduresList]).Refresh(); });
                //else
                //    ((CurrencyManager)dataGridView1.BindingContext[Library.Objects.ProjectSettings.Instance.ProceduresList]).Refresh();
                ReorderColumns();
            }
            button_ShowText.BringToFront();
        }

        private void ReorderColumns()
        {
            if (dataGridView1 != null && dataGridView1.Columns != null)
            {
                int index = 0;
                if (dataGridView1.Columns.Contains("Name"))
                    dataGridView1.Columns["Name"].DisplayIndex = index++;
                if (dataGridView1.Columns.Contains("DataType"))
                    dataGridView1.Columns["DataType"].DisplayIndex = index++;
                if (dataGridView1.Columns.Contains("DefaultValue"))
                    dataGridView1.Columns["DefaultValue"].DisplayIndex = index++;
                if (dataGridView1.Columns.Contains("Output"))
                    dataGridView1.Columns["Output"].DisplayIndex = index++;
                if (dataGridView1.Columns.Contains("Parent"))
                    dataGridView1.Columns["Parent"].Visible = false;
            }
        }
        //public delegate void OpenProcedureEventHandler(string[] files);
        //public delegate void OpenTextEditorEventHandler(string text);
        //public event OpenTextEditorEventHandler OpenText;

        private void button_ShowText_Click(object sender, EventArgs e)
        {
            try
            {
                _procedure.ShowText();
                //string[] filetab = {
                //                    ((Objects.Procedure)_procedure).f
                //Settings.Instance.ProjectSettings.OnOpenProcedure(this, new OpenFormEventArgs(_procedure.Text));
                //string[] strtab = { _procedure.FileLocalization };
                /*
                if (OpenProcedure != null)// && !(_procedure.FileLocalization == null || _procedure.FileLocalization == string.Empty))
                    OpenProcedure(this, new OpenFormEventArgs(_procedure));//OpenProcedure(_procedure);
                else
                    if (!string.IsNullOrWhiteSpace(_procedure.Text))
                    {
                        MessageBox.Show(_procedure.Text, _procedure.Name);
                        //if (OpenText != null)
                        //    OpenText(_procedure.BodyOfProcedure);
                    }
                */
            }
            catch (System.UnauthorizedAccessException ex)
            {
                //IntPtr accessToken = IntPtr.Zero;
                //if (LogonUser("testKonto", "mojaDomena", "AAAaaa1234", LOGON_TYPE_INTERACTIVE, LOGON_TYPE_PROVIDER_DEFAULT, ref accessToken))
                //{
                //    System.Security.Principal.WindowsIdentity identity = new System.Security.Principal.WindowsIdentity(accessToken);
                //    System.Security.Principal.WindowsImpersonationContext context = identity.Impersonate();
                //    //files = System.IO.Directory.GetFiles(@"\\zdalnySerwer\folder");
                //    context.Undo();
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void bt_DescribeVersion_Click(object sender, EventArgs e)
        {
            //Forms.DescribeVersions verDes = new Forms.DescribeVersions(this._procedure.Version._originalText);
            //verDes.Show();
            UserControls.EditProcedureVersion procVer = new UserControls.EditProcedureVersion(_procedure);

            System.Windows.Forms.Form tmpu = new System.Windows.Forms.Form();
            tmpu.AutoSize = true;
            tmpu.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            tmpu.Text = "NEW";
            tmpu.Controls.Add(procVer);
            tmpu.Show();
            tmpu.FormClosing += new System.Windows.Forms.FormClosingEventHandler(tmpu_FormClosing);
        }

        void tmpu_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            var tmpo = (System.Windows.Forms.Form)sender;
            foreach (var a in tmpo.Controls)
            {
                Type b = a.GetType();
                if (a.GetType() == typeof(UserControls.EditProcedureVersion))
                {
                    var tmpVer = ((UserControls.EditProcedureVersion)a).CreateNew();
                    //tmpVer.Parent = _procedure;
                    if (tmpVer != null)
                        ((Objects.Procedure)_procedure).ChangeVersion(tmpVer);
                }
            }
        }

        private const int LOGON_TYPE_INTERACTIVE = 2;
        private const int LOGON_TYPE_PROVIDER_DEFAULT = 0;

        // Using this api to get an accessToken of specific Windows User by its user name and password
        [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        static public extern bool LogonUser(string userName, string domain, string passWord,
              int logonType, int logonProvider, ref IntPtr accessToken);

    }
}
